package com.lifuping.fileupload.service;


import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import lombok.AllArgsConstructor;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

@Slf4j
@Component
@AllArgsConstructor
public class MinioStorageService {

    private static String url = "http://39.99.113.111:9000";  //minio服务的IP端口
    private static String accessKey = "admin";
    private static String secretKey = "123123123";
    private static String bucketName = "finance";
    /**
     * 上传文件
     */
    public String uploadFile(byte[] data, String filePath) throws InvalidPortException, InvalidEndpointException {
        MinioClient minioClient = new MinioClient(url, accessKey, secretKey);

        InputStream inputStream = new ByteArrayInputStream(data);
        String path = "";
        try {
            minioClient.putObject(bucketName, filePath, inputStream, inputStream.available(), getContextType(filePath));
            path = filePath;
        } catch (Exception e) {
            log.error("=====minio:"+e.getMessage());
        }
        return path;
    }


    /**
     * 删除文件
     */
    /*public boolean delete(String filePath) {
        try {
            client.removeObject(minioClient.getBucketName(),filePath);
            return true;
        } catch (Exception e) {
            log.error("====minio:删除失败，"+e.getMessage());
        }
        return false;
    }*/

    public String getContextType(String path){
        String suffix = path.substring(path.lastIndexOf(".") + 1 );
        String type = "application/octet-stream";
        if(suffix.equals("jpg")||suffix.equals("jpeg")||suffix.equals("png")||suffix.equals("bmp")||suffix.equals("gif")){
            type = "image/jpeg";
        }
        return type;
    }

}

